package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //检查用户是否登陆
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //SpringMvc启动时,将所有方法封装成handleMethod对象
        if (handler instanceof HandlerMethod){
            //只有动态请求才可以强转
            HandlerMethod hm = (HandlerMethod) handler;
            //判断方法上是否贴了@RequireLogin
            if (hm.hasMethodAnnotation(RequireLogin.class)){
                //先从cookie里面获取token
                String token = CookieUtil.getToken(request);
                //从redis里面获取userinfo
                UserInfo userInfo = userInfoRedisService.getUserInfoByToken(token);
                if (userInfo==null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
